package v1

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"server/internal/model"
	"server/pkg/app"
	"server/pkg/errcode"
	"server/utils"
)

// 用户登录
func Login(c *gin.Context) {
	_ = c.Request.ParseForm()
	u := &model.User{}
	_ = c.ShouldBind(u)

	if len(u.Name) == 0 {
		app.ToErrorResponse(c, errcode.UnauthorizedAuthNotExist)
		c.Abort()
		return
	}

	if len(u.PassWord) == 0 {
		app.ToErrorResponse(c, errcode.UnauthorizedAuthNotExist)
		c.Abort()
		return
	}

	u.PassWord = utils.EncodeMD5(u.PassWord)
	u.Info()
	owner := &model.Owner{
		Name: u.Name,
	}
	owner.Info()
	Projects := owner.Projects
	if owner.Name == "admin" {
		project := &model.Project{}
		Projects, _ = project.List()
	}
	if len(u.Name) == 0 {
		app.ToErrorResponse(c, errcode.UnauthorizedAuthNotExist)
		c.Abort()
	} else {
		token, err := app.GenerateToken(u.Name, u.PassWord)
		if err != nil {
			c.Abort()
		}
		SetCookie(c)
		c.JSON(http.StatusOK, gin.H{
			"token":     token,
			"role":      u.Role,
			"projects":  Projects,
			"tasks":     owner.Tasks,
			"pipelines": owner.PipeLines,
		})
	}
}

// 登出
func Logout(c *gin.Context) {
	DeleteCookie(c)
	c.JSON(http.StatusOK, gin.H{
		"msg": "登出成功",
	})
}

// 设置cookies
func SetCookie(c *gin.Context) {
	c.SetCookie("role", "cookievalue", 3600, "/", "localhost", false, true)
}

// 删除cookies
func DeleteCookie(c *gin.Context) {
	c.SetCookie("my_cookie", "cookievalue", -1, "/", "localhost", false, true)
}

// 获取cookies
func GetCookie(c *gin.Context) {
	data, err := c.Cookie("my_cookie")
	if err != nil {
		c.String(200, data)
		return
	}

}
